package com.zhkj.txg.module.product.popup

import android.content.Context
import android.graphics.Paint
import android.text.TextUtils
import android.util.Log
import android.view.Gravity
import android.view.View
import android.view.WindowManager
import android.view.animation.Animation
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import com.blankj.utilcode.util.TimeUtils
import com.zhkj.lib.utils.AccountManager
import com.zhkj.lib.utils.ScreenUtil
import com.zhkj.lib.utils.SpanUtil
import com.zhkj.lib.utils.ToastUtil
import com.zhkj.txg.R
import com.zhkj.txg.module.product.entity.ProductEntity2
import com.zhkj.txg.module.product.entity.SpecEntity
import com.zhkj.txg.module.product.entity.SpecPriceEntity
import com.zhkj.txg.module.product.ui.WatcherActivity
import com.zhkj.txg.utils.ImageUtils
import com.zhkj.txg.utils.TextWatcherWrapper
import razerdp.basepopup.BasePopupWindow

class ProductSpecPopupWindow(
    context: Context,
    val buyNow: (specId: Int, goodsNum: Int) -> Unit,
    val addCart: (specId: Int, goodsNum: Int) -> Unit
) : BasePopupWindow(context) {

    private var callback: OnSpecChangeCallback? = null
    private var ivSpec: ImageView? = null
    private var tvPrice: TextView? = null
    private var tvEarn: TextView? = null
    private var tvStock: TextView? = null
    private var viewBuy: View? = null
    private var etNum: EditText? = null
    private var btnCart: TextView? = null
    private var btnBuy: TextView? = null
    private var btnBuyNow: TextView? = null

    private val valueIdBuilder: StringBuilder = StringBuilder()

    private var productEntity: ProductEntity2? = null            // 商品的属性列表

//    private var groupType: Int = 0

    init {
        popupGravity = Gravity.BOTTOM
        setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING)
        setAutoShowInputMethod(false)
    }

    override fun onCreateContentView(): View = createPopupById(R.layout.popup_product_spec)
    override fun onViewCreated(contentView: View?) {
        ivSpec = contentView?.findViewById(R.id.ivProductSpec)
        tvPrice = contentView?.findViewById(R.id.tvProductPrice)
        tvEarn = contentView?.findViewById(R.id.tvProductEarn)
        tvStock = contentView?.findViewById(R.id.tvProductStock)
        viewBuy = contentView?.findViewById(R.id.viewBuy)
        btnCart = contentView?.findViewById(R.id.btnCart)
        btnBuy = contentView?.findViewById(R.id.btnBuy)
        btnBuyNow = contentView?.findViewById(R.id.btnBuyNow)

        contentView?.findViewById<View>(R.id.ivClose)?.setOnClickListener { dismiss() }
        // 设置ScrollView的高度
        contentView?.findViewById<View>(R.id.maxScroll)?.layoutParams?.height =
            (ScreenUtil.getScreenHeight(context) * 0.3).toInt()
        contentView?.findViewById<View>(R.id.btnBuyNow)?.setOnClickListener {
            if (etNum?.text?.toString()?.toInt() ?: 0 <= 0) {
                ToastUtil.show(context.getString(R.string.product_number_change))
                return@setOnClickListener
            }
            buyNow(0, etNum?.text?.toString()?.toInt() ?: 1)
            dismiss()
        }
        contentView?.findViewById<View>(R.id.btnBuy)?.setOnClickListener {
            if (etNum?.text?.toString()?.toInt() ?: 0 <= 0) {
                ToastUtil.show(context.getString(R.string.product_number_change))
                return@setOnClickListener
            }
            buyNow(0, etNum?.text?.toString()?.toInt() ?: 1)
            dismiss()
        }
        contentView?.findViewById<View>(R.id.btnCart)?.setOnClickListener {
            if (etNum?.text?.toString()?.toInt() ?: 0 <= 0) {
                ToastUtil.show(context.getString(R.string.product_number_change))
                return@setOnClickListener
            }
            addCart(0, etNum?.text?.toString()?.toInt() ?: 1)
            dismiss()
        }

        // 减号按钮
        contentView?.findViewById<View>(R.id.tvMinus)?.setOnClickListener {
            val numOrNull = etNum?.text?.toString()
            if (!numOrNull.isNullOrEmpty()) numOrNull.toInt().let {
                when {
                    it > 0 -> etNum?.setText((it - 1).toString())
                    else -> {
                        etNum?.setText("0")
                    }
                }
                etNum?.setSelection(etNum?.text?.length ?: 0)
            }
        }
        // 加号按钮
        contentView?.findViewById<View>(R.id.tvPlus)?.setOnClickListener {
            val numOrNull = etNum?.text?.toString()
            if (!numOrNull.isNullOrEmpty()) numOrNull.toInt().let {
                if (productEntity != null && productEntity?.shopCount ?: 99 < it) {
                    etNum?.setText((productEntity?.shopCount ?: 99).toString())
                    ToastUtil.show(context.getString(R.string.more_than_stock))
                } else etNum?.setText((it + 1).toString())
                etNum?.setSelection(etNum?.text?.length ?: 0)
            }
        }
        // 输入框监听
        etNum = contentView?.findViewById(R.id.etNum)
        etNum?.let {
            it.addTextChangedListener(TextWatcherWrapper { s ->
                if (s.isNullOrEmpty()) {
                    it.setText("0")
                    it.setSelection(1)
                } else if (s.length > 1 && s.startsWith('0')) s.delete(0, 1)
                else if (productEntity != null && productEntity?.shopCount ?: 99 < s.toString().toInt()) {
                    s.replace(0, s.length, (productEntity?.shopCount ?: 99).toString())
                    ToastUtil.show(context.getString(R.string.more_than_stock))
                }
            })
            it.setText("1")
            it.setSelection(1)
        }
        ivSpec?.setOnClickListener {
            WatcherActivity.open(
                context, arrayListOf(
                    productEntity?.image ?: ""
                ), 0
            )
        }
    }

    override fun onCreateShowAnimation(width: Int, height: Int): Animation {
        return getTranslateVerticalAnimation(1F, 0F, 400)
    }

    override fun onCreateDismissAnimation(): Animation {
        return getTranslateVerticalAnimation(0F, 1F, 400)
    }

    /**
     * 设置是否显示购买按钮
     */
    fun setMode(isBuy: Boolean, type: Int = 0) {
        if (isBuy) {
            viewBuy?.visibility = View.GONE
            btnBuyNow?.visibility = View.VISIBLE
        } else {
            viewBuy?.visibility = if (type == 0) View.VISIBLE else View.GONE
            btnBuyNow?.visibility = if (type == 0) View.GONE else View.VISIBLE
        }
//        btnBuyNow?.visibility = if (isBuy && type == 0) View.GONE else View.VISIBLE
//        viewBuy?.visibility = if (isBuy) View.VISIBLE else View.GONE
    }

    fun setMemberChoose() {
        viewBuy?.visibility = View.GONE
    }

    /**
     * 设置需要显示的数据
     */
    fun initData(
        productEntity: ProductEntity2
    ) {
        this.productEntity = productEntity
        fillData(productEntity)
    }

    /**
     * 数据填充
     */
    private fun fillData(productEntity: ProductEntity2) {
        ImageUtils.loadRoundCornerImage(
            context,
            ivSpec!!,
            productEntity.image
        )
        if (productEntity.activeType == 2) {
            tvPrice?.text = SpanUtil.setMoneySymbol(productEntity.activePrice)
        } else if (productEntity.activeType == 1) {
            if (TimeUtils.string2Millis(productEntity.startTime) < TimeUtils.getNowMills()) {
                tvPrice?.text = SpanUtil.setMoneySymbol(productEntity.activePrice)
            }
        } else {
            if (productEntity.cardType == "1") {
                tvPrice?.text = SpanUtil.setMoneySymbol(if (productEntity.plusPrice.isNullOrEmpty()) productEntity.price else productEntity.plusPrice)
            } else {
                tvPrice?.text = SpanUtil.setMoneySymbol(productEntity.price)
            }
        }
//        if (productEntity.shopsgoods?.activeType == 2) {
//            viewBuy?.visibility = View.VISIBLE
//            btnBuyNow?.visibility = View.VISIBLE
//        } else {
//            viewBuy?.visibility = View.GONE
//            btnBuyNow?.visibility = View.GONE
//        }
//        if (productEntity.shopsgoods == null) {
//            tvStock?.text = "库存:0"
//        } else {
//            tvStock?.text = "库存:${productEntity.shopCount}"
//        }
        tvStock?.text = "库存:${productEntity.shopCount}"
    }

    fun setOnSpecChangeCallback(callback: OnSpecChangeCallback) {
        this.callback = callback
    }
}

interface OnSpecChangeCallback {
    fun onSpecChange(selectSpec: SpecPriceEntity?)
}